package org.alino.core.shiro;

import org.alino.core.shiro.session.ShiroSessionRepository;
import org.alino.core.utils.LoggerUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;

import java.io.Serializable;
import java.util.Collection;

/**
 * @Desc Session 操作
 * @Author by Brant
 * @Date 2017/1/12
 */
public class AlinoShiroSessionDAO extends AbstractSessionDAO {

    private ShiroSessionRepository shiroSessionRepository;

    public ShiroSessionRepository getShiroSessionRepository() {
        return shiroSessionRepository;
    }

    public void setShiroSessionRepository(ShiroSessionRepository shiroSessionRepository) {
        this.shiroSessionRepository = shiroSessionRepository;
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session,sessionId);
        LoggerUtils.debug(getClass(),"创建seesion,id=[%s]",session.getId().toString());
        getShiroSessionRepository().saveSession(session);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable serializable) {
        LoggerUtils.debug(getClass(),"获取seesion,id=[%s]",serializable.toString());
        return getShiroSessionRepository().getSession(serializable);
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        LoggerUtils.debug(getClass(),"更新session，id=[%s]",session.getId().toString());
        getShiroSessionRepository().saveSession(session);
    }

    @Override
    public void delete(Session session) {
        LoggerUtils.debug(getClass(),"删除seesion,id=[%s]",session.getId().toString());
        if(session == null){
            LoggerUtils.error(getClass(),"Session 不能为 null");
        }
        Serializable sessionId = session.getId();
        if(sessionId!=null){
            getShiroSessionRepository().deleteSession(sessionId);
        }
    }

    @Override
    public Collection<Session> getActiveSessions() {
        return getShiroSessionRepository().getSessions();
    }
}
